package com.hzvdvmc.autosale.socket.manager;

import android.os.CountDownTimer;
import android.text.TextUtils;

import com.hzvdvmc.autosale.MyApp;
import com.hzvdvmc.autosale.common.TipConstant;
import com.hzvdvmc.autosale.constant.CmdEnum;
import com.hzvdvmc.autosale.constant.GlobleCache;
import com.hzvdvmc.autosale.constant.ResultEnum;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.constant.TimeConstant;
import com.hzvdvmc.autosale.seriaport.SerialCallback;
import com.hzvdvmc.autosale.seriaport.SerialClientManager;
import com.hzvdvmc.autosale.seriaport.SerialCmdEnum;
import com.hzvdvmc.autosale.socket.SaleCacheManager;
import com.hzvdvmc.autosale.socket.TempDataHelper;
import com.hzvdvmc.autosale.socket.event.CommonEvent;
import com.hzvdvmc.autosale.sale.bean.PaySuccessBean;
import com.hzvdvmc.autosale.seriaport.SeriaCmdRequestManager;
import com.hzvdvmc.autosale.socket.event.TipEvent;
import com.hzvdvmc.autosale.util.DeviceUtils;
import com.hzvdvmc.autosale.util.EncodeUtil;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.StringUtil;
import com.hzvdvmc.autosale.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.hzvdvmc.autosale.socket.TempDataHelper.OUTSTATE_UNOUT;

/**
 * Created by william on 2017/12/24.
 * 指令响应 处理
 */

public class CmdResponseManager {
    public static CmdResponseManager instance;
    private CountDownTimer countDownTimer;
    private SerialClientManager serialClientManager;
    private boolean isSaleOuting;//出货流程 是否 正在执行

    private CmdResponseManager(){

    }
    public static CmdResponseManager getInstance() {
        if (instance == null) {
            instance = new CmdResponseManager();
        }
        return instance;
    }

    public boolean isSaleOuting() {
        return isSaleOuting;
    }

    private String logFlag = "[handle response]:";

    /**
     * 根据异或条件校验数据可靠性
     *
     * @return
     */
    public static boolean checkResponse(String response) {
        //响应的异或数据
        String checkNumResp = response.substring(6, 8);
        //解密后的消息体
        String comandAndData = EncodeUtil.decoded(response.substring(8));
        LogUtil.i("收到指令解密后：" + comandAndData);
        String command = comandAndData.substring(0, 2);
        String data = comandAndData.substring(2);
        if (checkNumResp.equals(CheckNumUtil.getCheckNumHex(command, data))) return true;
        return false;
    }


    /**
     * socket下推响应
     *
     * @param response
     */
    public void handleResponse(String response) throws Exception {

        if (CmdEnum.KEEP_LIVE.getValue().equals(response)) {
            //保活指令
            return;
        }

        if (checkResponse(response)) {

            String comandAndData = EncodeUtil.decoded(response.substring(8));
            String command = comandAndData.substring(0, 2).toUpperCase();
            String data = comandAndData.substring(2);

            if (TextUtils.isEmpty(data)) {
                LogUtil.i("handleResponse: data is empty!!!");
                return;
            }
            //让人能看懂的字符数据
            String originData = StringUtil.convertHexToString(data);
            LogUtil.i("【response】 origin data:" + originData);
            if (TextUtils.isEmpty(originData)) {
                LogUtil.i("handleResponse: originData is empty!!!");
                return;
            }

            SocketRequestQuence.onReceivedData(command, originData);

            if (CmdEnum.KEEP_LIVE.getValue().equals(command)) {
                LogUtil.i(logFlag + CmdEnum.KEEP_LIVE.getDesc());
                //保活
            } else if (CmdEnum.HEARTBEAT.getValue().equals(command)) {
                LogUtil.p(logFlag + CmdEnum.HEARTBEAT.getDesc());
                //心跳
            } else if (CmdEnum.PAY_SUCCESS.getValue().equals(command)) {
                LogUtil.i(logFlag + CmdEnum.PAY_SUCCESS.getDesc() + LogUtil.nextLine);

                MyApp.stopSerialHeart();
                //支付成功
                String machineNO = originData.substring(0, 12);
                final String orderNO = originData.substring(12, 34);
                String tuneNO = originData.substring(34, 39);
                String payModeValue = originData.substring(39);
                LogUtil.p("订单号：" + orderNO + ";货道编号：" + tuneNO + ";支付方式：" + payModeValue);

                if (TempDataHelper.isChache(orderNO)){
                    return;
                }

                if (TempDataHelper.getTempList().size() > TempDataHelper.MAX_COUNT){
                    TempDataHelper.getTempList().remove(0);
                }

                //正在执行流程，直接返回，对新指令不做响应
                if (isSaleOuting){
                    return;
                }
                isSaleOuting = true;

                //刚开始，缓存就不为空，说明是上次设备异常，遗留的流程数据
                PaySuccessBean cache = SaleCacheManager.getCache();
                if (cache != null) {
                    //如果出货流程未启动，但是缓存有数据，说明设备 上次出货流程中发生了异常，视为失败，上报出货结果
                    reportOutReslut(cache.getOutResult(),cache.getOrderNO());
                    return;
                }

                PaySuccessBean bean = new PaySuccessBean();
                bean.setMachineNO(machineNO);
                bean.setOrderNO(orderNO);
                bean.setTuneNO(tuneNO);
                bean.setPayModeValue(payModeValue);
                bean.setOutState(OUTSTATE_UNOUT);

                SaleCacheManager.insertCache(bean);
                TempDataHelper.getTempList().add(bean);
                //普通应答
                CmdRequestManager.getInstance().paySuccessAnswerRequest(true);

                //未出货时
                EventBus.getDefault().post(new TipEvent("支付成功，正在验证..."));
                EventBus.getDefault().post(new CommonEvent(CommonEvent.PAY_SUCCESS));
                ToastUtils.showShort("支付成功，正在验证...");

                paySuccessVeri(orderNO, tuneNO);

            } else if (CmdEnum.CONTROL_RESTART.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_RESTART.getDesc());
                //重启
                String machineNO = originData.substring(0, 12);
                //重启校验
                CmdRequestManager.getInstance().commonVeriRequest(CmdEnum.CONTROL_RESTART_VERI);
                DeviceUtils.reboot("重启");

            } else if (CmdEnum.CONTROL_UPDATE.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_UPDATE.getDesc());
                //升级
                String machineNO = originData.substring(0, 12);
                String apkUrl = originData.substring(13);
                //校验
                CmdRequestManager.getInstance().commonVeriRequest(CmdEnum.CONTROL_UPDATE_VERI);
            } else if (CmdEnum.CONTROL_MODIFY_PRICE.getValue().equals(command)) {
                //修改价格
                LogUtil.p("response :" + CmdEnum.CONTROL_MODIFY_PRICE.getDesc());
                //校验
                CmdRequestManager.getInstance().commonAnswer(CmdEnum.CONTROL_MODIFY_PRICE, true);
//                CmdRequestManager.getInstance().commonVeriRequest(CmdEnum.CONTROL_MODIFY_PRICE_VERI);
            } else if (CmdEnum.CONTROL_SUPPLEMENT.getValue().equals(command)) {
                //补货通知
                ToastUtils.showShort("有补货");
                LogUtil.p("response :" + CmdEnum.CONTROL_SUPPLEMENT.getDesc());
                CmdRequestManager.getInstance().commonAnswer(CmdEnum.CONTROL_SUPPLEMENT, true);
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
//                CmdRequestManager.getInstance().commonVeriRequest(CmdEnum.CONTROL_SUPPLEMENT_VERI);
            } else if (CmdEnum.CONTROL_SUPPLEMENT_BY_ONE.getValue().equals(command)) {
                //一键补货通知
                ToastUtils.showShort("远程有一键补货");
                LogUtil.p("response :" + CmdEnum.CONTROL_SUPPLEMENT_BY_ONE.getDesc());
//                CmdRequestManager.getInstance().commonAnswer(CmdEnum.CONTROL_SUPPLEMENT_BY_ONE, true);
                //先不验证，直接刷新列表
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
//                CmdRequestManager.getInstance().commonVeriRequest(CmdEnum.CONTROL_SUPPLEMENT_BY_ONE_VERI);
                //
            } else if (CmdEnum.CONTROL_SHOPLIST_REFRESH.getValue().equals(command)) {
                //刷新列表通知
                ToastUtils.showShort("列表需要刷新");
                LogUtil.p("response :" + CmdEnum.CONTROL_SHOPLIST_REFRESH.getDesc());
                CmdRequestManager.getInstance().commonAnswer(CmdEnum.CONTROL_SHOPLIST_REFRESH, true);
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
//                CmdRequestManager.getInstance().commonVeriRequest(CmdEnum.CONTROL_SHOPLIST_REFRESH_VERI);
            } else if (CmdEnum.CONTROL_INVENTORY_SETTING.getValue().equals(command)) {
                LogUtil.p("response :" + CmdEnum.CONTROL_INVENTORY_SETTING.getDesc());
            } else if (CmdEnum.CONTROL_ADVERTISEMENT.getValue().equals(command)) {
                //广告方案更新
                LogUtil.p("response :" + CmdEnum.CONTROL_ADVERTISEMENT.getDesc());
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_ADVERTISEMENT));
            } else if (CmdEnum.CONTROL_SYSTEM_PARAM.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_SYSTEM_PARAM.getDesc());

            } else if (CmdEnum.REPORT_CLEAR_ERROR.getValue().equals(command)) {

                //人工清楚故障
                LogUtil.p("response :" + CmdEnum.REPORT_CLEAR_ERROR.getDesc());

            } else if (CmdEnum.REPORT_POWER_ON.getValue().equals(command)) {

                //机器通电
                LogUtil.p("response :" + CmdEnum.REPORT_POWER_ON.getDesc());

            } else if (CmdEnum.REPORT_POWER_OFF.getValue().equals(command)) {
                //机器断电
                LogUtil.p("response :" + CmdEnum.REPORT_POWER_OFF.getDesc());

            } else if (CmdEnum.REPORT_OPEN_DOOR.getValue().equals(command)) {
                //开门
                LogUtil.p("response :" + CmdEnum.REPORT_OPEN_DOOR.getDesc());

            } else if (CmdEnum.REPORT_CLOSE_DOOR.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REPORT_CLOSE_DOOR.getDesc());

            } else if (CmdEnum.REPORT_SUPPLEMENT_BY_ONE.getValue().equals(command)) {
                //一键补货
                LogUtil.p("response :" + CmdEnum.REPORT_SUPPLEMENT_BY_ONE.getDesc());
                String machineNO = originData.substring(0, 12);
                String result = originData.substring(12);

                if (ResultEnum.Success.getValue().equals(result)) {
                    //一键补货成功
                    EventBus.getDefault().post(new CommonEvent(CommonEvent.ONE_KEY_SUPP));
                } else {
                    EventBus.getDefault().post(new CommonEvent(CommonEvent.ONE_KEY_SUPP_FAIL));
                }

            } else if (CmdEnum.REPORT_SUPPLEMENT_BY_DETAIL.getValue().equals(command)) {
                LogUtil.p("response :" + CmdEnum.REPORT_SUPPLEMENT_BY_DETAIL.getDesc());


            } else if (CmdEnum.REPORT_SHOPWAY_COMPACITY.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REPORT_SHOPWAY_COMPACITY.getDesc());

            } else if (CmdEnum.REPORT_SHOPWAY_LIST.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REPORT_SHOPWAY_LIST.getDesc());

            } else if (CmdEnum.REPORT_UPDATE_ADVERTISEMENT.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REPORT_UPDATE_ADVERTISEMENT.getDesc());

            } else if (CmdEnum.REQUEST_MODIFY_PARAMS.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REQUEST_MODIFY_PARAMS.getDesc());

            } else if (CmdEnum.REQUEST_HAVE_SALE.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REQUEST_HAVE_SALE.getDesc());

            } else if (CmdEnum.REQUEST_MODIFY_PRICE.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REQUEST_MODIFY_PRICE.getDesc());

            } else if (CmdEnum.REQUEST_MODIFY_INVENTORY.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REQUEST_MODIFY_INVENTORY.getDesc());

            } else if (CmdEnum.REQUEST_UPDATE_ADVERTISEMENT.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REQUEST_UPDATE_ADVERTISEMENT.getDesc());

            } else if (CmdEnum.REQUEST_MODIFY_SHOPSTATE.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REQUEST_MODIFY_SHOPSTATE.getDesc());

            } else if (CmdEnum.REPORT_ERROR.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.REPORT_ERROR.getDesc());

            } else if (CmdEnum.CONTROL_RESTART_VERI.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_RESTART_VERI.getDesc());

            } else if (CmdEnum.CONTROL_UPDATE_VERI.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_UPDATE_VERI.getDesc());

            } else if (CmdEnum.CONTROL_MODIFY_PRICE_VERI.getValue().equals(command)) {
                LogUtil.p("response :" + CmdEnum.CONTROL_MODIFY_PRICE_VERI.getDesc());
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
            } else if (CmdEnum.CONTROL_SUPPLEMENT_VERI.getValue().equals(command)) {
                LogUtil.p("response :" + CmdEnum.CONTROL_SUPPLEMENT_VERI.getDesc());
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
            } else if (CmdEnum.CONTROL_SUPPLEMENT_BY_ONE_VERI.getValue().equals(command)) {
                LogUtil.p("response :" + CmdEnum.CONTROL_SUPPLEMENT_BY_ONE_VERI.getDesc());
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
            } else if (CmdEnum.CONTROL_SHOPLIST_REFRESH_VERI.getValue().equals(command)) {
                LogUtil.p("response :" + CmdEnum.CONTROL_SHOPLIST_REFRESH_VERI.getDesc());
                EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));

            } else if (CmdEnum.CONTROL_INVENTORY_SETTING_VERI.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_INVENTORY_SETTING_VERI.getDesc());

            } else if (CmdEnum.CONTROL_ADVERTISEMENT_VERI.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_ADVERTISEMENT_VERI.getDesc());

            } else if (CmdEnum.CONTROL_SYSTEM_PARAM_VERI.getValue().equals(command)) {

                LogUtil.p("response :" + CmdEnum.CONTROL_SYSTEM_PARAM_VERI.getDesc());

            }
        } else {
            ToastUtils.showShort("数据解析失败");
        }
    }

    /**
     * 收到下推指令，开始验证操作
     *
     * @param orderNO
     * @param tuneNO
     */
    private void paySuccessVeri(final String orderNO, String tuneNO) {
        String requestData = CmdRequestManager
                .getInstance().getSuccessVeriCmdData(orderNO);

        SocketRequest socketQuence = new SocketRequest(CmdEnum.PAY_SUCCESS_VERIFICATION);
        socketQuence.setOrderNO(orderNO);
        socketQuence.setTuneNO(tuneNO);
        socketQuence.equence(requestData, new SocketLisenter() {

            @Override
            public void onResponse(String response, String tuneNO, String orderNO) {
                payVeriResult(response, tuneNO, orderNO);
            }

            @Override
            public void onError(String data) {
                ToastUtils.showShort("支付验证无效，请注意查收退款");
                reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
            }
        });
    }

    private void payVeriResult(String originData, String tuneNO, final String orderNO) {
        LogUtil.p(logFlag + CmdEnum.PAY_SUCCESS_VERIFICATION.getDesc() + LogUtil.nextLine);
        //支付成功校验
        String machineNO = originData.substring(0, 12);
        String result = originData.substring(12);
        if (ResultEnum.Success.getValue().equals(result)) {
            //校验成功，出货
            LogUtil.p("支付校验成功，准备出货..." + tuneNO);
            ToastUtils.showShort("验证成功，正在出货...");
            TempDataHelper.setOutStateByOrderNO(orderNO, TempDataHelper.OUTSTATE_OUTING);
            EventBus.getDefault().post(new CommonEvent(CommonEvent.REFRESH_LIST));
            EventBus.getDefault().post(new CommonEvent(CommonEvent.PAY_VERI_SUCCESS));
            EventBus.getDefault().post(new TipEvent("验证成功，准备出货..."));
            String dataOutWare = SeriaCmdRequestManager.getInstacne().getDataOutWare(tuneNO, false);

            SerialClientManager serialClientManager = new SerialClientManager();
            serialClientManager.setOrderNO(orderNO);
            serialClientManager.setTuneNO(tuneNO);
            serialClientManager.setCallback(SerialCmdEnum.OUT_WARE, new SerialCallback() {

                @Override
                public void onSuccess(String cmd, String data, String tuneNO, String orderNO) {
                    outWareAnswerSuccess(data, tuneNO, orderNO);
                }

                @Override
                public void onFile(String msg, String tuneNO, String orderNO) {
                    LogUtil.p("串口出货请求超时，出货失败。");
                    ToastUtils.showShort(msg);
                    //串口超时，出货失败
                    EventBus.getDefault().post(new CommonEvent(CommonEvent.SERIL_OUT_TIME));
                    reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
                }
            }).setData(dataOutWare).execute();

        } else {
            //校验失败
            EventBus.getDefault().post(new TipEvent("支付验证失败！"));
            EventBus.getDefault().post(new CommonEvent(CommonEvent.PAY_VERI_FAILURE));
            ToastUtils.showShort("支付验证失败");
            reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
        }
    }

    /**
     * 串口出货应答成功
     *
     * @param data
     * @param shopWayNO
     */
    private void outWareAnswerSuccess(String data, String shopWayNO, String orderNO) {
        String address = data.substring(0, 2);
        String result = data.substring(2);
        if (ResultEnum.Success.getValue().equals(result)) {
            //应答成功,查询出货结果
            startCheckTask(shopWayNO, orderNO);
        } else if (ResultEnum.Fail.getValue().equals(result)) {
            //表示串口流水码重复，说明机器已在处理，同上开始查询任务
            startCheckTask(shopWayNO, orderNO);
        } else {
            //应答失败，发送出货指令，驱动板故障
            LogUtil.p("串口出货应答返回结果，为故障状态。");
            ToastUtils.showShort("机器故障，出货失败");
            EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_FALIURE));
            reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
        }
    }

    /**
     * 查询出货结果
     *
     * @param shopWayNO
     */
    private void startCheckTask(final String shopWayNO, final String orderNO) {

        countDownTimer = new CountDownTimer(TimeConstant.OUTRESULT_WAIT, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                LogUtil.p("查询出货结果time" + millisUntilFinished);
                checkExecute(shopWayNO, orderNO,countDownTimer);
            }

            @Override
            public void onFinish() {

                LogUtil.p("串口查询出货结果：出货失败");
                ToastUtils.showShort("出货失败");
                EventBus.getDefault().post(new TipEvent(TipConstant.out_fail));
                EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_FALIURE));
                reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
                countDownTimer.cancel();
            }
        };

        checkExecute(shopWayNO,orderNO, countDownTimer);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                countDownTimer.start();
            }
        },500);

    }

    private void checkExecute(final String shopWayNO, String orderNO,final CountDownTimer countDownTimer) {
        if (serialClientManager != null) {
            serialClientManager.stopTimeOutTask();
        }

        serialClientManager = new SerialClientManager();
        serialClientManager.setOrderNO(orderNO);
        serialClientManager.setTuneNO(shopWayNO);
        serialClientManager.setCallback(SerialCmdEnum.CHECK_OUT_WARE_RESULT,
                new SerialCallback() {
                    @Override
                    public void onSuccess(String cmd, String data, String tuneNO, String orderNO) {

                        String address = data.substring(0, 2);
                        String result = data.substring(2, 3);
                        String state = StringUtil.convertStringToHex(result);
                        String isDown = StringUtil.convertStringToHex(data.substring(3));
                        boolean isInfrared = SPUtils.getInstance().getBoolean(SpKey.INFRARED_RAY);
                        LogUtil.p("查询到的出货结果是：" + state + ",红外装置=" + isInfrared);


                        if ("30".equals(state)) {
                            //成功出货
                            if (isInfrared) {
                                //有红外并下落
                                if ("1".equals(isDown)) {
                                    EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_SUCCESS));
                                    LogUtil.p("有红外，出货成功");
                                    ToastUtils.showShort("出货成功");
                                    countDownTimer.cancel();
                                    reportOutReslut(ResultEnum.Success.getValue(), orderNO);
                                    TempDataHelper.setOutStateByOrderNO(orderNO, TempDataHelper.OUTSTATE_SUCCESS);
                                }

                            } else {

                                EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_SUCCESS));
                                LogUtil.p("无红外，出货成功");
                                ToastUtils.showShort("出货成功");
                                countDownTimer.cancel();
                                reportOutReslut(ResultEnum.Success.getValue(), orderNO);
                                TempDataHelper.setOutStateByOrderNO(tuneNO, TempDataHelper.OUTSTATE_SUCCESS);
                            }

                        } else if (state.startsWith("3")) {
                            //正在出货
                            ToastUtils.showShort("正在出货...");
                            EventBus.getDefault().post(new TipEvent(TipConstant.out_ing));
                            ToastUtils.showShort(TipConstant.out_ing);

                        } else if (state.startsWith("5")) {

                            if (isInfrared) {
                                //有红外并下落
                                if ("1".equals(isDown)) {
                                    EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_SUCCESS));
                                    LogUtil.p("有红外，出货成功");
                                    ToastUtils.showShort("出货成功");
                                    countDownTimer.cancel();
                                    reportOutReslut(ResultEnum.Success.getValue(), orderNO);
                                    TempDataHelper.setOutStateByOrderNO(orderNO, TempDataHelper.OUTSTATE_SUCCESS);
                                    return;
                                }
                            }

                            //出货失败
                            LogUtil.p("串口查询出货结果：出货失败");
                            ToastUtils.showShort(TipConstant.out_fail);
                            EventBus.getDefault().post(new TipEvent(TipConstant.out_fail));
                            EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_FALIURE));
                            reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
                        }
                    }


                    @Override
                    public void onFile(String msg, String tuneNO, String orderNO) {
                        LogUtil.p("出货失败:" + msg);
                        ToastUtils.showShort("出货失败:" + msg);
                        EventBus.getDefault().post(new TipEvent(msg));
                        EventBus.getDefault().post(new CommonEvent(CommonEvent.SERIL_OUT_TIME));
                        reportOutReslut(ResultEnum.Fail.getValue(), orderNO);
                    }
                }).setData(SeriaCmdRequestManager.getInstacne().getCheckDataWareResul(shopWayNO))
                .execute();
    }

    private int count = 0;

    /**
     * 上报出货结果
     */
    public void reportOutReslut(final String result, final String orderNO) {
        if (countDownTimer!=null){
            countDownTimer.cancel();
        }
        count ++;
        //失败情况下，上报5次，流程结束
        if (count > 5){
            SaleCacheManager.clearCache();
            isSaleOuting = false;
            MyApp.startSerialHeart();
            count = 0;
            return;
        }

        SaleCacheManager.updateCache(result, SaleCacheManager.order_state_out_success);

        String data = CmdRequestManager.getInstance().getResultReportCmdData(result, orderNO);
        SocketRequest request = new SocketRequest(CmdEnum.REPORT_SALE_RESULT);
        request.equence(data, new SocketLisenter() {
            @Override
            public void onResponse(String response, String tuneNO, String orderNO) {
                //上报出货结果
                if (ResultEnum.Success.getValue().equals(response)) {
                    EventBus.getDefault().post(new TipEvent("出货结果 上报成功"));
                    //流程结束
                    SaleCacheManager.clearCache();
                    isSaleOuting = false;
                    count = 0;
                    MyApp.startSerialHeart();
                } else {
                    //上报出货结果，应答失败，继续上报
                    EventBus.getDefault().post(new TipEvent("出货结果 上报失败（服务端错误）"));
                    EventBus.getDefault().post(new CommonEvent(CommonEvent.OUT_FALIURE));
                    reportOutReslut(result, orderNO);
                }
            }

            @Override
            public void onError(String data) {
                ToastUtils.showShort("出货结果 上报失败:" + data);
                reportOutReslut(result, orderNO);
            }
        });

    }

}
